package com.mspbots.teams.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mspbots.api.client.CoreClient;
import com.mspbots.teams.model.TriggerEventDTO;
import com.mspbots.teams.model.UtilizationDTO;
import com.mspbots.teams.service.UtilizationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitMessagingTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.Map;

import static com.mspbots.common.TriggerEvent.TEAMS_UTILIZATION;

@Slf4j
@Service
public class UtilizationServiceImpl implements UtilizationService {

    @Autowired
    private CoreClient coreClient;
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private RabbitMessagingTemplate messagingTemplate;

    @Override
    public boolean check(UtilizationDTO utilizationDTO) {
        boolean result = false;
        Map<String, Object> userMappingParam = Map.of(
                "tenantId", utilizationDTO.getTenantId(),
                "tenantUserId", utilizationDTO.getTenantUserId()
        );
        JsonNode userMapping = coreClient.get("/user-mapping/detail", userMappingParam).block();
        if (!ObjectUtils.isEmpty(userMapping)) {
            ObjectMapper mapper = new ObjectMapper();

            try {
                String json = mapper.writeValueAsString(utilizationDTO);
                JsonNode payload = mapper.readTree(json);
                TriggerEventDTO triggerEventDTO = new TriggerEventDTO();
                triggerEventDTO.setTenantId(userMapping.get("tenantId").asLong());
                triggerEventDTO.setEventName(TEAMS_UTILIZATION.getEvent());
                triggerEventDTO.setScope(TEAMS_UTILIZATION.getScope());
                triggerEventDTO.setPayload(payload);
                triggerEventDTO.setUserInfo(userMapping);
                this.messagingTemplate.convertAndSend("msp.trigger.event", "", triggerEventDTO);
                log.debug("cw msp.trigger.event Escalation[{}] ", this.objectMapper.convertValue(triggerEventDTO, JsonNode.class));
                result = true;
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
        }

        return result;
    }


}
